package com.example.webdemo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@RestController
@RequestMapping("/api/assistant")
public class AssistantController {

    private final RestTemplate restTemplate;
    private final Map<String, List<Map<String, String>>> conversationHistory = new HashMap<>();

    @Value("${deepseek.api.url}")
    private String apiUrl;

    @Value("${deepseek.api.key}")
    private String apiKey;

    public AssistantController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    // 与AI助手对话
    @PostMapping("/chat")
    public ResponseEntity<Map<String, Object>> chatWithAssistant(
            @RequestBody Map<String, Object> request) {

        try {
            String userId = (String) request.get("userId");
            String message = (String) request.get("message");
            boolean newConversation = (boolean) request.getOrDefault("newConversation", false);

            if (userId == null || userId.isEmpty() || message == null || message.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("参数不完整"));
            }

            // 获取或初始化对话历史
            List<Map<String, String>> history = conversationHistory.get(userId);
            if (history == null || newConversation) {
                history = new ArrayList<>();
                // 添加系统提示
                history.add(Map.of("role", "system", "content", "你是一个专业的客户关系管理助手，帮助用户生成与客户沟通的模板。请保持回复简洁、专业且友好。"));
                conversationHistory.put(userId, history);
            }

            // 添加用户消息
            history.add(Map.of("role", "user", "content", message));

            // 准备请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", history);
            requestBody.put("temperature", 0.7);
            requestBody.put("max_tokens", 2000);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 发送请求
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, Map.class);

            // 处理响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                if (choices != null && !choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    Map<String, String> messageMap = (Map<String, String>) choice.get("message");
                    String content = messageMap.get("content");

                    // 添加助手回复到历史
                    history.add(Map.of("role", "assistant", "content", content));

                    // 创建响应
                    Map<String, Object> responseMap = new HashMap<>();
                    responseMap.put("success", true);
                    responseMap.put("message", content);
                    responseMap.put("conversationId", userId);

                    return ResponseEntity.ok(responseMap);
                }
            }

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("无法获取AI响应"));

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("处理请求时出错: " + e.getMessage()));
        }
    }

    // 获取对话历史
    @GetMapping("/history/{userId}")
    public ResponseEntity<Map<String, Object>> getConversationHistory(
            @PathVariable String userId) {

        List<Map<String, String>> history = conversationHistory.get(userId);
        if (history != null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("history", history);
            return ResponseEntity.ok(response);
        }
        return ResponseEntity.ok(Map.of(
                "success", true,
                "history", Collections.emptyList()
        ));
    }

    // 清除对话历史
    @DeleteMapping("/history/{userId}")
    public ResponseEntity<Map<String, Object>> clearConversationHistory(
            @PathVariable String userId) {

        conversationHistory.remove(userId);
        return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "对话历史已清除"
        ));
    }

    // 获取预定义模板类型
    @GetMapping("/template-types")
    public ResponseEntity<Map<String, Object>> getTemplateTypes() {
        List<String> templates = Arrays.asList(
                "产品介绍",
                "客户跟进",
                "问题解决",
                "促销活动",
                "满意度调查",
                "续约提醒",
                "VIP专属优惠",
                "节假日问候",
                "投诉处理",
                "合同续签"
        );

        return ResponseEntity.ok(Map.of(
                "success", true,
                "templates", templates
        ));
    }

    // 生成特定模板
    @PostMapping("/generate-template")
    public ResponseEntity<Map<String, Object>> generateTemplate(
            @RequestBody Map<String, Object> request) {

        try {
            String templateType = (String) request.get("templateType");
            String customerName = (String) request.get("customerName");
            String productName = (String) request.get("productName");
            String companyName = (String) request.get("companyName");

            if (templateType == null || templateType.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("模板类型不能为空"));
            }

            // 构建提示词
            StringBuilder prompt = new StringBuilder("请生成一个专业的" + templateType + "模板");

            Map<String, String> params = new HashMap<>();
            if (customerName != null && !customerName.isEmpty()) {
                prompt.append("，客户名称是").append(customerName);
                params.put("客户姓名", customerName);
            }
            if (productName != null && !productName.isEmpty()) {
                prompt.append("，产品名称是").append(productName);
                params.put("产品名称", productName);
            }
            if (companyName != null && !companyName.isEmpty()) {
                prompt.append("，公司名称是").append(companyName);
                params.put("公司名称", companyName);
            }

            // 准备请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", Collections.singletonList(
                    Map.of("role", "user", "content", prompt.toString())
            ));
            requestBody.put("temperature", 0.5);
            requestBody.put("max_tokens", 1500);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 发送请求
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, Map.class);

            // 处理响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                if (choices != null && !choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    Map<String, String> messageMap = (Map<String, String>) choice.get("message");
                    String content = messageMap.get("content");

                    // 创建响应
                    Map<String, Object> responseMap = new HashMap<>();
                    responseMap.put("success", true);
                    responseMap.put("template", content);
                    responseMap.put("parameters", params);
                    responseMap.put("type", templateType);

                    return ResponseEntity.ok(responseMap);
                }
            }

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("无法生成模板"));

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("处理请求时出错: " + e.getMessage()));
        }
    }

    // 分析客户沟通内容
    @PostMapping("/analyze-conversation")
    public ResponseEntity<Map<String, Object>> analyzeConversation(
            @RequestBody Map<String, Object> request) {

        try {
            String conversation = (String) request.get("conversation");

            if (conversation == null || conversation.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("对话内容不能为空"));
            }

            // 构建提示词
            String prompt = "请分析以下客户沟通内容，并提供改进建议和后续行动方案：\n\n" + conversation;

            // 准备请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", Collections.singletonList(
                    Map.of("role", "user", "content", prompt)
            ));
            requestBody.put("temperature", 0.6);
            requestBody.put("max_tokens", 2000);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 发送请求
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, Map.class);

            // 处理响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                if (choices != null && !choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    Map<String, String> messageMap = (Map<String, String>) choice.get("message");
                    String content = messageMap.get("content");

                    // 创建响应
                    Map<String, Object> responseMap = new HashMap<>();
                    responseMap.put("success", true);
                    responseMap.put("analysis", content);

                    return ResponseEntity.ok(responseMap);
                }
            }

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("无法分析对话内容"));

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("处理请求时出错: " + e.getMessage()));
        }
    }

    // 创建错误响应
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("error", message);
        return response;
    }
}